﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace ClientSocket {
    public class StateObject {
        public Socket workSocket;
        public const int BufferSize = 1024;
        public byte[] buffer = new byte[BufferSize];
    }
    class ClientServer {
        public static string ip = "192.168.0.104";
        public static int port = 8081;
        public static Socket client = null;
        public static void StartConnect () {
            try {
                IPAddress ipaddress = IPAddress.Parse (ip);
                IPEndPoint ipendpoint = new IPEndPoint (ipaddress, port);
                client = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                client.BeginConnect (ipendpoint, new AsyncCallback (ConnectCallback), client);
            } catch (System.Exception) {

                throw;
            }

        }

        private static void ConnectCallback (IAsyncResult ar) {
            try {
                Socket client = (Socket) ar.AsyncState;
                client.EndConnect (ar);
                Console.WriteLine ("连接到远程服务器成功");
            } catch (System.Exception) {

                throw;
            }
        }
        public static void Send (String data) {
            byte[] bytedata = Encoding.UTF8.GetBytes (data);
            client.BeginSend (bytedata, 0, bytedata.Length, 0, new AsyncCallback (SendCallback), client);
        }
        private static void SendCallback (IAsyncResult ar) {
            try {
                Socket client = (Socket) ar.AsyncState;
                int bytesent = client.EndSend (ar);
                Console.WriteLine ("发送了{0}个字节信息：", bytesent);
            } catch (System.Exception) {

                throw;
            }
        }
    }
    class Program {
        static void Main (string[] args) {
            StringBuilder count = new StringBuilder ();
            ClientServer.StartConnect ();
            while (true) {
                if (Console.ReadKey ().Key == ConsoleKey.S) {
                    Console.WriteLine ("发送");
                    for (int i = 0; i < 100; i++) {
                        count.Append ("中国" + i);
                    }
                    ClientServer.Send (count.ToString ());
                }
            }
        }
    }
}